/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.configuration;

import com.workcell.workdata.im.mvc.resolver.OriginArgumentResolver;
import com.workcell.workdata.im.mvc.resolver.TokenArgumentResolver;
import com.workcell.workdata.im.mvc.resolver.UidArgumentResolver;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MvcConfiguration extends OncePerRequestFilter implements WebMvcConfigurer, WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Resource
    private HandlerInterceptor tokenInterceptor;

    @Resource
    private HandlerInterceptor originInterceptor;

    @Resource
    private HandlerInterceptor fileInterceptor;

    private final List<String> apiPathList = new ArrayList<>();

    public MvcConfiguration(){
        apiPathList.add("/base/**");
        apiPathList.add("/comment/**");
        apiPathList.add("/micro/**");
        apiPathList.add("/moment/**");
        apiPathList.add("/group/**");
        apiPathList.add("/message/**");
        apiPathList.add("/config/**");
        apiPathList.add("/code/**");
        apiPathList.add("/friend/**");
        apiPathList.add("/apns/**");
        apiPathList.add("/tag/**");
        apiPathList.add("/file/**");
        apiPathList.add("/user/**");
        apiPathList.add("/webrtc/**");
        apiPathList.add("/account/**");
        apiPathList.add("/emoticon/**");
        apiPathList.add("/note/**");
        apiPathList.add("/chat/*");
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(originInterceptor)
                .order(0)
                .addPathPatterns("/**");

        registry.addInterceptor(tokenInterceptor)
                .order(1)
                .addPathPatterns(apiPathList);

        registry.addInterceptor(fileInterceptor).order(0)
                .addPathPatterns("/file/**");
    }


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new TokenArgumentResolver());
        argumentResolvers.add(new UidArgumentResolver());
        argumentResolvers.add(new OriginArgumentResolver());
    }

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401"));
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"));
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
        factory.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error/405"));
        factory.addErrorPages(new ErrorPage(HttpStatus.PAYLOAD_TOO_LARGE, "/error/413"));
        factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
    }



    @Bean
    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);
        configuration.addExposedHeader(HttpHeaders.CONTENT_DISPOSITION);
        source.registerCorsConfiguration("/**", configuration);

        return new CorsFilter(source);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse);
    }
}